import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/enums/resource_type.dart';

import 'package:sainbainu/common/values/colors.dart';
import 'package:sainbainu/common/widgets/widget.dart';
import 'package:sainbainu/view/content_detail/widgets/bottom_action_bar.dart';
import 'package:sainbainu/view/content_detail/widgets/comment_bottom_sheet.dart';
import 'package:sainbainu/view/content_detail/widgets/comment_item.dart';
import 'package:sainbainu/view/content_detail/widgets/detail_content.dart';
import 'package:sainbainu/view/content_detail/widgets/separator_line.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

import 'index.dart';
import 'widgets/share_menu.dart';

class ContentDetailPage extends GetView<ContentDetailController> {
  const ContentDetailPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ContentDetailController>(builder: (_) {
      return Scaffold(
        body: _buildBody(
          (physics) => [
            SliverAppBar(
              title: Text('帖子详情'.tr),
              floating: true,
            ),
            SliverToBoxAdapter(
              child: DetailContent(key: _.state.commentInputKey),
            ),
            const SliverToBoxAdapter(
              child: SizedBox(height: 10),
            ),
            SliverToBoxAdapter(
              child: _buildCommentAreaTitle(),
            ),
            GetBuilder<ContentDetailController>(
              id: 'commentList',
              builder: (_) => _buildCommentList(_),
            ),
          ],
        ),
        // 底部评论点赞栏
        bottomNavigationBar: BottomActionBar(
          onLikeTap: (isGive) => _.onGiveHandle(
            isGive,
            resourceId: _.state.noteId,
            resourceType: ResourceType.content,
          ),
          onCollectionTap: (isGive) => _.onCollectionHandle(
            isGive,
            resourceId: _.state.noteId,
            resourceType: ResourceType.content,
          ),
          onCommentTap: () => _onShowCommentAddSheet(
            context,
            resourceId: _.state.noteId,
            resourceType: ResourceType.content,
          ),
          onShareTap: () => showShareBottomSheet(),
        ),
      );
    });
  }

  /// 页面容器
  Widget _buildBody(
    List<Widget> Function(ScrollPhysics physics) sliversBuilder,
  ) {
    return KeyboardClose(
      child: EasyRefresh.builder(
        controller: controller.state.commentRefreshController,
        onLoad: controller.onCommentRichBottom,
        childBuilder: (context, physics) {
          return CustomScrollView(
            physics: physics,
            // controller: controller.state.scrollController,
            controller: controller.state.autoScrollController,
            slivers: sliversBuilder(physics),
          );
        },
      ),
    );
  }

  /// 评论区域标题
  Widget _buildCommentAreaTitle() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.all(15),
      child: GetBuilder<ContentDetailController>(
        id: 'commentTotal',
        builder: (_) => Text(
          '${'评论'.tr}(${_.state.commentListResponse.total})',
          style: const TextStyle(
            color: AppColors.active,
            fontSize: 15,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  /// 评论列表
  SliverList _buildCommentList(ContentDetailController _) {
    return SliverList.separated(
      itemCount: _.state.commentListResponse.rows.length,
      itemBuilder: (BuildContext context, int index) {
        var item = _.state.commentListResponse.rows[index];
        return AutoScrollTag(
          key: ValueKey(index),
          controller: _.state.autoScrollController,
          index: index,
          child: CommentItem(
            item: item,
            showReplyButton: true,
            showDelIcon: true,
            onReplyTap: (item) {
              _.setCurrentCommentInfo(item);
              _onShowReplyCommentListSheet(context);
            },
            onPreviewTap: _.handlePreviewImage,
            onLikeTap: (isGive, id) => _.onGiveHandle(
              isGive,
              resourceId: id,
              resourceType: ResourceType.comment,
            ),
            onDelTap: (id) => _.onCommentDel(
              commentId: id,
              resourceType: ResourceType.content,
            ),
            onUserTap: (customerId) => _.toUserDetailPage(customerId),
          ),
        );
      },
      separatorBuilder: (context, index) {
        return const SeparatorLine();
      },
    );
  }

  /// 显示评论回复列表
  void _onShowReplyCommentListSheet(BuildContext context) {
    showBarModalBottomSheet(
      context: context,
      // 如果子组件是滚动组件 则下拉关闭会很费劲 所以调整一下关闭阈值
      closeProgressThreshold: 0.85,
      builder: (context) => KeyboardClose(
        child: CommentBottomSheet(
          onLikeTap: (isGive, id) => controller.onGiveHandle(
            isGive,
            resourceId: id,
            resourceType: ResourceType.comment,
          ),
          onInputTap: (commentId) => _onShowCommentAddSheet(
            context,
            resourceId: commentId,
            resourceType: ResourceType.comment,
          ),
          onDelTap: (id) => controller.onCommentDel(
            commentId: id,
            resourceType: ResourceType.comment,
          ),
          onUserTap: (customerId) => controller.toUserDetailPage(customerId),
        ),
      ),
    );
  }

  /// 显示评论输入框
  void _onShowCommentAddSheet(
    BuildContext context, {
    int? resourceId,
    int? resourceType,
  }) {
    // 每次打开清空内容
    controller.handleResetComment();
    // 聚焦使其弹出软键盘
    controller.state.focusNode.requestFocus();

    showBarModalBottomSheet(
      context: context,
      barrierColor: Colors.black54,
      builder: (context) {
        return KeyboardClose(
          child: AnimatedPadding(
            padding: EdgeInsets.only(
              bottom: MediaQuery.of(context).viewInsets.bottom,
            ),
            duration: Duration.zero,
            child: Container(
              padding: const EdgeInsets.fromLTRB(15, 15, 15, 0),
              decoration: const BoxDecoration(
                color: AppColors.page,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10),
                  topRight: Radius.circular(10),
                ),
              ),
              child: SafeArea(
                top: false,
                bottom: true,
                minimum: const EdgeInsets.only(bottom: 15),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    OutlinedFormBox(
                      child: TextField(
                        controller: controller.state.commentEditingController,
                        focusNode: controller.state.focusNode,
                        maxLength: 140,
                        maxLines: 3,
                        decoration: InputDecoration(
                          hintText: '请输入'.tr,
                          border: InputBorder.none,
                          contentPadding: const EdgeInsets.all(0),
                        ),
                      ),
                    ),
                    OutlinedFormBox(
                      child: ImageUploader(
                        controller: controller.state.imageUploaderController,
                        maxCount: 1,
                        selectedCallback: (images) {
                          controller.commentImageChange(images);
                        },
                      ),
                    ),
                    OutlinedFormBox(
                      child: Recorder(
                        controller: controller.state.customRecorderController,
                        recordedCallback: (path, duration) {
                          controller.commentAudioChange(path, duration);
                        },
                        recordRemoveCallback: () {
                          controller.commentAudioChange(null, null);
                        },
                      ),
                    ),
                    GetBuilder<ContentDetailController>(
                      id: 'commentSubmit',
                      builder: (_) {
                        return SizedBox(
                          width: double.infinity,
                          height: 44,
                          child: ElevatedButton(
                            onPressed: _.state.disabledCommentSubmit
                                ? null
                                : () => _.onCommentSubmit(
                                      resourceId: resourceId,
                                      resourceType: resourceType,
                                    ),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: AppColors.danger,
                              foregroundColor: Colors.white,
                              enableFeedback: true,
                            ),
                            child: Text('发布'.tr),
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 分享弹窗
  showShareBottomSheet() {
    showBarModalBottomSheet(
      context: Get.context!,
      builder: (context) {
        return ShareMenu(
          enableMenus: const [
            ShareMenuType.wechatSession,
            ShareMenuType.wechatTimeline,
            ShareMenuType.wechatFavorite,
          ],
          onCancelTap: () => Get.back(),
          onMenuTap: (ShareMenuType type) => controller.onShareWeChat(type),
        );
      },
    );
  }
}
